package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.fastjson.JSON;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.MD5Utils;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * projectName:day15_myxiaomi
 * author:lcy
 * time:2023/11/26 9:38
 * description:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {

    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");

        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "register.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "register.jsp";
        }
        if (!password.equals(repassword)) {
            request.setAttribute("msg", "两次密码不一致");
            return "register.jsp";
        }
        if (StringUtils.isEmpty(email)) {
            request.setAttribute("msg", "邮箱不能为空");
            return "register.jsp";
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {
            request.setAttribute("msg", "用户名已存在");
            return "register.jsp";
        }
        User user = new User(0, username, password, email, gender, 1, 1, RandomUtils.createActive());
        try {
            userService.register(user);

            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "注册失败");
            return "register.jsp";
        }
    }

    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        String auto = request.getParameter("auto");

        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "message.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "message.jsp";
        }
        if (StringUtils.isEmpty(vcode)) {
            request.setAttribute("msg", "验证码不能为空");
            return "message.jsp";
        }
        String code = (String) request.getSession().getAttribute("vcode");
        if (!vcode.equalsIgnoreCase(code)) {
            request.setAttribute("msg", "验证码错误");
            return "message.jsp";
        }

        try {
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            request.getSession().setAttribute("user", user);

            System.out.println(auto);
            if (auto != null) {
                String userInfo = username + "#" + password;

                userInfo = Base64Utils.encode(userInfo);

                Cookie cookie = new Cookie("userInfo", userInfo);
                cookie.setPath(request.getContextPath());

                cookie.setMaxAge(14 * 24 * 60 * 60);

                cookie.setHttpOnly(true);

                response.addCookie(cookie);
            }

            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "用户登录失败" + e.getMessage());
            return "message.jsp";
        }
    }

    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);

        ValidateCode validateCode = new ValidateCode(100, 28, 4, 20);
        request.getSession().setAttribute("vcode", validateCode.getCode());
        System.out.println(validateCode.getCode());

        validateCode.write(response.getOutputStream());
        return null;
    }

    /**
     * 验证用户是否存在
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");
            return null;
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {
            response.getWriter().write("1");
            return null;
        }
        response.getWriter().write("0");
        return null;
    }

    public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("user");

        session.invalidate();

        Cookie cookie = new Cookie("userInfo", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:/index.jsp";
    }

    /*----------------------------------地址模块-----------------------------------*/
    //userservlet?method=addAddress
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "login.jsp";
        }
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收货人不能为空");
            return "address_info.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "收货人电话不能为空");
            return "address_info.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收货人地址不能为空");
            return "address_info.jsp";
        }
        try {
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(0, detail, name, phone, user.getId(), 0);
            addressService.add(address);

            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加地址失败：" + e.getMessage());
            return "address_info.jsp";
        }
    }

    //serservlet?method=getAddress
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());
            request.setAttribute("addList", addList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "address_info.jsp";
    }

    //userservlet?method=deleteAddress&id=7
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "删除id不能为空");
            return "address_info.jsp";
        }
        try {
            AddressService addressService = new AddressServiceImpl();
            addressService.remove(user.getId(), Integer.parseInt(id));

            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除地址失败：" + e.getMessage());
            return "address_info.jsp";
        }
    }

    //userservlet?method=defaultAddress&id=7
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        try {
            AddressService addressService = new AddressServiceImpl();
            addressService.updateLevel(user.getId(), Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.getStackTrace();
            request.setAttribute("msg", "设置默认地址失败：" + e.getMessage());
            return "address_info.jsp";
        }
    }

    //userservlet?method=updateAddress
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "地址编号不能为空");
            return "address_info.jsp";
        }
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "姓名不能为空");
            return "address_info.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "电话号码不能为空");
            return "address_info.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "详细地址不能为空");
            return "address_info.jsp";
        }
        try {
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(Integer.parseInt(id), detail, name, phone, user.getId(), Integer.parseInt(level));
            addressService.update(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新地址失败：" + e.getMessage());
            return "address_info.jsp";
        }
    }

    //--------------------------------------------------后台管理系统登录-----------------------------------------------------------
    //userservlet?method=adminLogin
    public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "admin/message.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "admin/message.jsp";
        }
        try {
            //String s = MD5Utils.md5(password);
            //System.out.println(s);
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            request.getSession().setAttribute("user", user);
            return "admin/admin.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "登录失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }

    //userservlet?method=getUserList
    public String getUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //response.setContentType("application/json;charset=utf-8");
        System.out.println("进来了");
        //response.setContentType("application/jsom;charset=utf-8");
        //System.out.println("进来了");
        //User user = (User) request.getSession().getAttribute("admin");
        //if(user==null){
        //    return "redirect:userservlet?method=adminLogin";
        //}
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        String invalidUser = request.getParameter("invalidUser");
        List<Object> params = new ArrayList<>();
        StringBuilder where = new StringBuilder("where 1=1");

        if (!StringUtils.isEmpty(username)) {
            where.append(" AND `username` LIKE ?  ");
            params.add("%" + username + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            where.append(" AND `gender`=? ");
            params.add(gender);
        }
        //if(StringUtils.isEmpty(username)){
        //    request.setAttribute("msg", "用户名不能为空");
        //    return "admin/message.jsp";
        //}
        //if(StringUtils.isEmpty(gender)){
        //    request.setAttribute("msg", "性别不能为空");
        //    return "admin/message.jsp";
        //}
        boolean flag = false;
        if (!StringUtils.isEmpty(invalidUser) && "true".equals(invalidUser)) {
            flag = true;
        }
        try {
            UserService userService = new UserServiceImpl();
            //List<User> userList=userService.findName(username,gender);
            List<User> userList = userService.findUserInfo(where.toString(), params, flag);
            if (userList != null && !userList.isEmpty()) {
                String josn = JSON.toJSONString(userList);
                System.out.println(josn);
                response.getWriter().write(josn);
            }

            //request.setAttribute("userList",userList);
            return null;
            //return "/admin/userList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "会员管理查看失败：" + e.getMessage());
            return "admin/message.jsp";
        }


        //User user = (User) request.getSession().getAttribute("admin");
        //if (user == null) {
        //    return "redirect:admin/login.jsp";
        //}

        //response.setContentType("application/jsom;charset=utf-8");
        //String username = request.getParameter("username");
        //String gender = request.getParameter("gender");
        //String invalidUser = request.getParameter("invalidUser");
        //List<Object> params = new ArrayList<>();
        //StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        //
        //if (!StringUtils.isEmpty(username)) {
        //    where.append(" AND username LIKE ? ");
        //    params.add("%"+username+"%");
        //}
        //if (!StringUtils.isEmpty(gender)) {
        //    where.append(" AND gender=? ");
        //    params.add(gender);
        //}
        //boolean flag = false;
        //if (!StringUtils.isEmpty(invalidUser) && "true".equals(invalidUser)){
        //    flag = true;
        //}
        //try {
        //    UserService userService=new UserServiceImpl();
        //    List<User> userList = userService.findUserInfo(where.toString(),params,flag);
        //    System.out.println(userList);
        //    if (userList != null && !userList.isEmpty()) {
        //        String jsonString = JSON.toJSONString(userList);
        //        System.out.println(jsonString);
        //        response.getWriter().write(jsonString);
        //    }
        //} catch (IOException e) {
        //    response.getWriter().write("查询信息失败"+e.getMessage());
        //}
        //return null;

    }

    //userservlet?method=deleteUser&id=
    public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if(StringUtils.isEmpty(id)){
            request.setAttribute("msg",  "删除id不能为空");
            return "admin/message.jsp";
        }
        try {
            UserService userService=new UserServiceImpl();
            int did = Integer.parseInt(id);
            userService.removeId(did);
            return null;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除失败：" + e.getMessage());
            return "admin/message.jsp";
        }
    }

}
